package router

import (
	cedar_session "github.com/tungyao/cedar-session"
	"github.com/tungyao/spruce"
	"log"
	"net/http"
	"time"
)

//
func CreateApp(w http.ResponseWriter, r *http.Request, session cedar_session.Session) {
	account := r.URL.Query().Get("account")
	password := r.URL.Query().Get("password")
	if !CheckAccount(account, password) {
		ToErrorJson(w, "auth failed")
		return
	}
	app := &ImCreateApp{
		Appid:  createRandStr(12),
		Secret: createRandStr(24),
	}
	stmt, err := DB.Prepare("insert into app set appid=?,secret=?,account=?,create_time=?")
	if err != nil {
		ToErrorJson(w, err.Error())
		return
	}
	_, err = stmt.Exec(app.Appid, app.Secret, account, time.Now().Unix())
	if err != nil {
		ToErrorJson(w, err.Error())
		return
	}
	o, err := app.MarshalJSON()
	if err != nil {
		ToErrorJson(w, err.Error())
		return
	}
	W(w, o)
}
func CheckAccount(account, password string) bool {
	// 这里使用 数据库验证就行了 并发量很低的
	ac := &ImAccount{}
	password = string(spruce.MD5([]byte(password)))
	stmt, err := DB.Prepare("select * from account where account=? and password=?")
	if err != nil {
		return false
	}
	row := stmt.QueryRow(account, password)
	row.Scan(&ac.Id, &ac.Account, &ac.Password, &ac.Create_time)
	if password != ac.Password {
		return false
	}
	return true
}

// 读出app数据到etcd
func readAppToEtcd() {
	rows, err := DB.Query("select * from app")
	if err != nil {
		log.Fatalln(err)
	}
	defer rows.Close()
	app := &ImCreateApp{}
	for rows.Next() {
		rows.Scan(&app.Id, &app.Appid, &app.Secret, &app.Account, &app.CreateTime)
		EtcdPut("/app/"+app.Appid, app.Secret)
	}
	rows.Close()
}
